package com.ruicar.afs.cloud.manage.common.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruicar.afs.cloud.basic.api.corporate.dto.BasicPenaltyExemptDto;
import com.ruicar.afs.cloud.basic.api.corporate.fegin.CorporateTransferFeign;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.modules.contract.enums.BusinessUrlEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.CaseStatusEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.ContractBusinessEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.ProcessStatusEnum;
import com.ruicar.afs.cloud.common.util.EmptyUtils;
import com.ruicar.afs.cloud.manage.common.entity.ManagePenaltyExempt;
import com.ruicar.afs.cloud.manage.common.entity.ManagePenaltyExemptDetails;
import com.ruicar.afs.cloud.manage.common.mapper.ManagePenaltyExemptMapper;
import com.ruicar.afs.cloud.manage.common.service.ManagePenaltyExemptDetailsService;
import com.ruicar.afs.cloud.manage.common.service.ManagePenaltyExemptService;
import com.ruicar.afs.cloud.manage.common.util.CreatCaseNoUtil;
import com.ruicar.afs.cloud.manage.penaltyexempt.condition.ManagePenaltyExemptCondition;
import com.ruicar.afs.cloud.manage.workflow.entity.WorkTaskCreatedInfo;
import com.ruicar.afs.cloud.manage.workflow.enums.NormalSubmitEnum;
import com.ruicar.afs.cloud.manage.workflow.enums.WorkflowTypeEnum;
import com.ruicar.afs.cloud.manage.workflow.processor.ContractWorkFlowSaveApproveInfoProcessor;
import com.ruicar.afs.cloud.manage.workflow.service.WorkTaskCreatedInfoService;
import com.ruicar.afs.cloud.manage.workflow.service.WorkflowSubmitService;
import com.ruicar.afs.cloud.manage.workflow.vo.TaskSubmitVO;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.request.StartFlowRequest;
import com.ruicar.afs.cloud.workflow.gwt.service.WorkflowService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * @author: Lee
 * @date 2020-05-30 04:45:15
 * @description
 */
@Slf4j
@AllArgsConstructor
@Service
public class ManagePenaltyExemptServiceImpl extends ServiceImpl<ManagePenaltyExemptMapper, ManagePenaltyExempt> implements ManagePenaltyExemptService {

    private final ManagePenaltyExemptDetailsService managePenaltyExemptDetailsService;
    private final ContractWorkFlowSaveApproveInfoProcessor saveApproveInfoProcessor;
    private WorkTaskCreatedInfoService workTaskCreatedInfoService;
    private final CorporateTransferFeign corporateTransferFeign;
    private final WorkflowSubmitService workflowSubmitService;
    private final WorkflowService workflowService;

    @Override
    public void savePenaltyExempt(ManagePenaltyExemptCondition managePenaltyExempt) {
        //保存信息
        if (managePenaltyExempt.getId() == null) {
            // 生成案件编号
            managePenaltyExempt.setCaseNo(CreatCaseNoUtil.GeneratorCaseNo(ContractBusinessEnum.exemptTypes));
            //更改状态
            managePenaltyExempt.setProcessStatus(ProcessStatusEnum.draft);
            managePenaltyExempt.setApplyDate(DateUtil.date());
            managePenaltyExempt.setApplyBy(SecurityUtils.getUser().getUserRealName());
            save(managePenaltyExempt);
            if (EmptyUtils.isNotEmpty(managePenaltyExempt.getManagePenaltyExemptDetails())) {
                for (ManagePenaltyExemptDetails penaltyExemptDetails : managePenaltyExempt.getManagePenaltyExemptDetails()) {
                    penaltyExemptDetails.setPenaltyId(managePenaltyExempt.getId());
                    penaltyExemptDetails.setId(null);
                    managePenaltyExemptDetailsService.save(penaltyExemptDetails);
                }
            }
        } else {
            ManagePenaltyExempt penaltyExempt = getById(managePenaltyExempt.getId());
            if (!ProcessStatusEnum.draft.equals(penaltyExempt.getProcessStatus())
                    && !ProcessStatusEnum.toBeRepaired.equals(penaltyExempt.getProcessStatus())) {
                throw new AfsBaseException(CommonConstants.FAIL, "此合同编号已流程中！");
            }
            updateById(managePenaltyExempt);
            if (EmptyUtils.isNotEmpty(managePenaltyExempt.getManagePenaltyExemptDetails())) {
                for (ManagePenaltyExemptDetails penaltyExemptDetails : managePenaltyExempt.getManagePenaltyExemptDetails()) {
                    managePenaltyExemptDetailsService.updateById(penaltyExemptDetails);
                }
            }
        }
    }

    @Override
    public void submitPenaltyExempt(ManagePenaltyExemptCondition managePenaltyExempt) {
        if (managePenaltyExempt.getId() == null) {
            throw new AfsBaseException(CommonConstants.FAIL, "单笔罚息豁免信息请保存！");
        }

        //提交审核，发起流程
        managePenaltyExempt.setProcessStatus(ProcessStatusEnum.underReview);
        managePenaltyExempt.setId(managePenaltyExempt.getId());
        updateById(managePenaltyExempt);
        if (EmptyUtils.isNotEmpty(managePenaltyExempt.getManagePenaltyExemptDetails())) {
            for (ManagePenaltyExemptDetails penaltyExemptDetails : managePenaltyExempt.getManagePenaltyExemptDetails()) {
                managePenaltyExemptDetailsService.updateById(penaltyExemptDetails);
            }
        }
        //保存合同信息变更申请记录
        //保存待办任务记录
        saveApproveInfoProcessor.saveApproveInfo(managePenaltyExempt, ContractBusinessEnum.exemptTypes,
                CaseStatusEnum.UNDER_REVIEW, BusinessUrlEnum.PENALTY_EXEMPT);
        StartFlowRequest startFlowRequest = new StartFlowRequest();
        startFlowRequest.setAfsFlowKey(AfsEnumUtil.key(WorkflowTypeEnum.PENALTY_EXEMPT));
        startFlowRequest.setBizDataId(String.valueOf(managePenaltyExempt.getId()));
        startFlowRequest.setFlowName((StringUtils.isEmpty(managePenaltyExempt.getContractNo()) ? "" : (managePenaltyExempt.getContractNo()) + "-") + AfsEnumUtil.desc(WorkflowTypeEnum.PENALTY_EXEMPT));
        String json = JSONObject.toJSONString(managePenaltyExempt);
        JSONObject cancelJson = JSONObject.parseObject(json);
        //保存审批记录
        TaskSubmitVO vo = new TaskSubmitVO();
        vo.setBizData(cancelJson);
        workflowSubmitService.saveRecord(vo, AfsEnumUtil.desc(NormalSubmitEnum.SUGGEST_CHECK_FINAL));
        //开始流程
        workflowService.startWorkFlow(startFlowRequest, cancelJson);
    }

    @Override
    public Boolean approvePenaltyExempt(ManagePenaltyExemptCondition managePenaltyExempt) {
        Boolean flag = false;

        CaseStatusEnum CaseStatus;
        ProcessStatusEnum processStatus;

        //更新处理状态
        if (AfsEnumUtil.key(NormalSubmitEnum.SUGGEST_CHECK_FINAL).equals(managePenaltyExempt.getApprovalOperating())) {
            WorkTaskCreatedInfo workTaskCreatedInfo = workTaskCreatedInfoService.getOne(Wrappers.<WorkTaskCreatedInfo>query().lambda()
                    .eq(WorkTaskCreatedInfo::getBizDataId, String.valueOf(managePenaltyExempt.getId())));
            if (ProcessStatusEnum.approved.name().equals(workTaskCreatedInfo.getTaskMemo())) {
                managePenaltyExempt.setEndDate(DateUtil.date());
                CaseStatus = CaseStatusEnum.APPROVED;
                processStatus = ProcessStatusEnum.approved;
                BasicPenaltyExemptDto basicPenaltyExemptDto = new BasicPenaltyExemptDto();
                BeanUtils.copyProperties(managePenaltyExempt, basicPenaltyExemptDto);
                corporateTransferFeign.updatePenaltyInterest(basicPenaltyExemptDto);
                flag = true;
            } else {
                CaseStatus = CaseStatusEnum.UNDER_REVIEW;
                processStatus = ProcessStatusEnum.underReview;
            }
            managePenaltyExempt.setProcessStatus(processStatus);
            //保存待办任务记录
            //保存合同信息变更申请记录
            saveApproveInfoProcessor.saveApproveInfo(managePenaltyExempt, ContractBusinessEnum.exemptTypes,
                    CaseStatus, BusinessUrlEnum.PENALTY_EXEMPT);
        } else if (AfsEnumUtil.key(NormalSubmitEnum.SUGGEST_REJECT_FINAL).equals(managePenaltyExempt.getApprovalOperating())) {
            managePenaltyExempt.setEndDate(DateUtil.date());
            managePenaltyExempt.setProcessStatus(ProcessStatusEnum.refuse);
            //保存合同信息变更申请记录
            //保存待办任务记录
            saveApproveInfoProcessor.saveApproveInfo(managePenaltyExempt, ContractBusinessEnum.exemptTypes,
                    CaseStatusEnum.REFUSE, BusinessUrlEnum.PENALTY_EXEMPT);
        }
        updateById(managePenaltyExempt);

        //流程审批
        TaskSubmitVO vo = new TaskSubmitVO();
        String json = JSONObject.toJSONString(managePenaltyExempt);
        JSONObject cancelJson = JSONObject.parseObject(json);
        vo.setBizData(cancelJson);
        vo.setApprovalOperating(managePenaltyExempt.getApprovalOperating());
        vo.setApprovalOpinion(managePenaltyExempt.getApprovalOpinion());
        vo.setReasonType(managePenaltyExempt.getReasonType());
        workflowSubmitService.submit(vo);
        return flag;
    }

    @Override
    public IPage getPenaltyExemptList(Page page, ManagePenaltyExemptCondition condition) {
        return this.baseMapper.getPenaltyExemptList(page, condition);
    }
}
